#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
# @Time    : 2022/4/25 20:02
# @Author  : 闫峰
# @Email   : 1603453211@qq.com
# @File    : testcase_template
# @describe: 用例模板
"""

import datetime
import os
from backend.utils.readFileUtils.yaml_control import GetYamlData
from backend.utils.settings import ensure_path_sep
from backend.utils.other_tools.exceptions import ValueNotFoundError


def write_case(case_path, page):
    """ 写入用例数据 """
    with open(case_path, 'w', encoding="utf-8") as file:
        file.write(page)


def write_testcase_file(*, case_dir, class_title,
                        func_title, case_path):
    """

        :param allure_story:
        :param file_name: 文件名称
        :param allure_epic: 项目名称
        :param allure_feature: 模块名称
        :param class_title: 类名称
        :param func_title: 函数名称
        :param case_path: case 路径
        :param case_ids: 用例ID
        :return:
        """
    conf_data = GetYamlData(ensure_path_sep("\\conf\\config.yaml")).get_yaml_data()
    try:
        api1_data = GetYamlData(file_dir=case_dir).get_yaml_data().get("case_common")
    except:
        print(case_dir)
        raise
    epic_name = api1_data.get("epic_name")
    feature_name = api1_data.get("feature_name")
    now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    real_time_update_test_cases = conf_data['real_time_update_test_cases']

    page = f'''#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time   : {now}
import time
import allure
import pytest
from utils.other_tools.handle_setup import BaseTool
from utils.other_tools.regular_control import build_param, regular
from utils.requests_tool.testBase import *
from utils.readFileUtils.yaml_control import GetYamlData

base = BaseTool()

@allure.epic("{epic_name}")
@allure.feature("{feature_name}")
class Test{class_title}:

    api_data = GetYamlData(file_dir=r"{case_dir}").get_yaml_data().get("case")  # dict
    api_data = regular(str(api_data))
    api_data = eval(api_data)

    @pytest.mark.parametrize('api_data', api_data)
    def test_{func_title}(self, api_data, init_Basetest):
        allure.dynamic.title(api_data['name'])
        db_name = api_data["db_name"]
        setup_sql = api_data['setup_sql']
        teardown_sql = api_data["teardown_sql"]
        # 执行前置sql 查询结果保存到cache
        if db_name:
            if setup_sql:
                for sql in setup_sql:
                    sql = build_param(sql)
                    base.execute_setup_sql(db_name, sql)

        name = build_param(api_data["name"])
        host = build_param(api_data["host"])
        url = build_param(api_data["url"])
        url = host + url
        method = api_data["method"]
        headers = build_param(api_data["headers"])
        headers = base.ast(headers)
        requestType = api_data["requestType"]
        data = build_param(api_data["data"])
        # data = base.ast(data)

        # saves = api_data["saves"]
        # assert_context = api_data["assert_context"]
        INFO.logger.info("\\n用例描述====>" + name)

        res = None
        # 判断接口请求类型

        if method.upper() == 'GET':
            res = init_Basetest.get_request(url=url, params=data, headers=headers)
        elif method.upper() == 'POST':
            if requestType.upper() == 'JSON':
                res = init_Basetest.post_request(url=url, headers=headers, json=data)
            elif requestType.upper() == 'DATA':
                res = init_Basetest.post_request(url=url, headers=headers, data=data)
            elif requestType.upper() == 'PARAMS':
                res = init_Basetest.post_request(url=url, headers=headers, params=data)
        # elif method.upper() == 'UPLOAD':
        #     res = init_Basetest.upload_request(url=url, headers=headers, cookies=cookies, params=params, data=body,
        #                                        files=file)
        elif method.upper() == 'PUT':
            res = init_Basetest.put_request(url=url, headers=headers, data=data)
        elif method.upper() == 'DELETE':
            res = init_Basetest.delete_request(url=url, headers=headers, data=data)
        else:
            pass  # 待扩展
        assert res.status_code == 200
        # 是否需要保存响应结果到cache
        saves = api_data["saves"]  
        if saves:
            base.save_data(res, saves)

        # 执行后置sql  查询结果保存到cache
        if db_name:
            if teardown_sql:
                for sql in teardown_sql:
                    sql = build_param(sql)
                    base.execute_teardown_sql(db_name, sql)
        # 断言
        sleep_time = api_data.get("sleep")
        if sleep_time:
            time.sleep(sleep_time)
        else:
            time.sleep(1)
        base.handler_assert(api_data.get("assert_context", []), res)
'''
    if real_time_update_test_cases:
        write_case(case_path=case_path, page=page)
    elif real_time_update_test_cases is False:
        if not os.path.exists(case_path):
            write_case(case_path=case_path, page=page)
    else:
        raise ValueNotFoundError("real_time_update_test_cases 配置不正确，只能配置 True 或者 False")
